﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Yuebon.Commons.Helpers;
using Yuebon.Commons.Json;
using Yuebon.Commons.Models;
using Yuebon.Commons.Options;
using Yuebon.Security.IServices;
using Yuebon.Security.Models;
using Yuebon.WebApi.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Yuebon.WebApi.Controllers
{
    /// <summary>
    /// Token令牌接口控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class TokenController : ControllerBase
    {
        private IAPPService iAPPService;
        private readonly JwtOption _jwtModel;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_iAPPService"></param>
        /// <param name="jwtModel"></param>
        public TokenController(IAPPService _iAPPService, JwtOption jwtModel)
        {
            if (_iAPPService == null)
                throw new ArgumentNullException(nameof(_iAPPService));
            iAPPService = _iAPPService;
            _jwtModel = jwtModel;
        }

        /// <summary>
        /// 获得token令牌
        /// </summary>
        /// <param name="grant_type">获取access_token填写client_credential</param>
        /// <param name="appid">用户唯一凭证，应用AppId</param>
        /// <param name="secret">应用密钥AppSecret</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get(string grant_type, string appid, string secret)
        {
            CommonResult result = new CommonResult();
            if (!grant_type.Equals(GrantType.ClientCredentials))
            {
                result.ErrCode = "40003";
                result.ErrMsg = ErrCode.err40003;
                return ToJsonContent(result);
            }
            else if(string.IsNullOrEmpty(grant_type))
            {
                result.ErrCode = "40003";
                result.ErrMsg = ErrCode.err40003;
                return ToJsonContent(result);
            }
            string strHost = Request.Host.ToString();
            APP app = iAPPService.GetAPP(appid, secret);
            if (app == null)
            {
                result.ErrCode = "40001";
                result.ErrMsg = ErrCode.err40001;
            }
            else
            {
                if (app.RequestUrl != strHost && !strHost.Contains("localhost"))
                {
                    result.ErrCode = "40002";
                    result.ErrMsg = ErrCode.err40002+"，你当前请求主机："+strHost;
                }
                else
                {
                    TokenProvider tokenProvider = new TokenProvider(_jwtModel);
                    TokenResult tokenResult = await tokenProvider.GenerateToken(grant_type, appid, secret);
                    return ToJsonContent(tokenResult);
                }
            }
            return ToJsonContent(result);
        }

        /// <summary>
        /// 验证token的合法性。
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost("CheckToken")]
        public IActionResult CheckToken(string token)
        {

            CommonResult result = new CommonResult();
            TokenProvider tokenProvider = new TokenProvider();
            result = tokenProvider.ValidateToken(token);
            return ToJsonContent(result);
        }
        /// <summary>
        /// 把object对象转换为ContentResult
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/ToJsonContent")]
        protected IActionResult ToJsonContent(object obj)
        {
            string result = JsonConvert.SerializeObject(obj, Formatting.Indented);
            return Content(obj.ToJson());
        }

    }
}
